package com.jia.lidao.others.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;
import com.jia.lidao.Constans;
import com.jia.lidao.R;
import com.jia.lidao.RunningContext;
import com.jia.lidao.UserUtils;
import com.jia.lidao.enity.QuickCalculate;
import com.jia.lidao.enity.UPPayBeen;
import com.jia.lidao.enity.WeiChatPayBeen;
import com.jia.lidao.network.http.BusinessManager;
import com.jia.lidao.others.API;
import com.jia.lidao.others.AddressActivity;
import com.jia.lidao.others.BaseFragment;
import com.jia.lidao.others.UserInfoUtil;
import com.jia.lidao.others.enity.Address;
import com.jia.lidao.others.enity.AliPayBeen;
import com.jia.lidao.others.enity.Channels;
import com.jia.lidao.others.enity.CountCash;
import com.jia.lidao.others.enity.ModelBeen;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.jia.lidao.others.enity.QuickOrder;
import com.jia.lidao.others.enity.ShoppingCartBeen;
import com.jia.lidao.others.ui.ChoosePayWayActivity;
import com.jia.lidao.others.ui.view.MineGoodsView;
import com.jia.lidao.others.utils.GsonUtils;
import com.jia.lidao.ui.WebActivity;
import com.jia.lidao.utils.LogUtil;
import com.jia.lidao.utils.WXEntryUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.jia.lidao.others.ui.fragment.ShoppingCartFragment.REFLUSH_COUNT;

//import static com.jia.lidao.others.ui.fragment.ShoppingCartFragment2.REFLUSH_COUNT;


/**
 * Created by 00029935 on 2017/11/19.
 */

public class EditOrderFormFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_people)
    TextView tvPeople;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_people_infor)
    RelativeLayout rlPeopleInfor;
    @BindView(R.id.tv_invoice)
    TextView tvInvoice;
    @BindView(R.id.tv_daijinquan)
    TextView tvDaijinquan;
    @BindView(R.id.rl_daijinquan)
    RelativeLayout rlDaijinquan;
    @BindView(R.id.rl_pay)
    RelativeLayout rlPay;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.ll_goods_content)
    LinearLayout llGoodsContent;
    @BindView(R.id.iv_way_pay)
    TextView ivWayPay;
    private Address.AddressesBean.DataBean address;
    private List<ShoppingCartBeen.MerchantsBean> data;
    private double totalPrice;
    private static final int CHOICE_WAY = 0x186;
    private StringBuffer shopCarIds = new StringBuffer();
    private Channels.PaymentChannelsBean bean;
    private IWXAPI iwxapi;
    // “00” – 银联正式环境
    // “01” – 银联测试环境，该环境中不发生真实交易
    private String serverMode = "01";
    private int couponId = 0;
    private boolean isQuickOrder = false;
    private QuickOrder quickOrder = null;
    public static final String KEY_QUICK_ORDER = "key_quick_order";
    private double payMoney = 0;
    //代金券金额
    private double money;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data = (List<ShoppingCartBeen.MerchantsBean>) getActivity().getIntent().getSerializableExtra("goods");
        totalPrice = getActivity().getIntent().getDoubleExtra("price", 0);
        iwxapi = WXAPIFactory.createWXAPI(getContext(), Constans.APP_ID);
        // 将该app注册到微信
        iwxapi.registerApp(Constans.APP_ID);

        String prodInfo = getActivity().getIntent().getStringExtra(KEY_QUICK_ORDER);
        if (!TextUtils.isEmpty(prodInfo)) {
            Log.e("HQQ", "prodInfo: " + prodInfo);
            TypeToken<QuickOrder> typeToken = new TypeToken<QuickOrder>() {
            };
            quickOrder = GsonUtils.fromJson(prodInfo, typeToken);
            isQuickOrder = true;
        }

    }

    @Override
    protected int getInflateLayout() {
        return R.layout.adit_order_form_fragment;
    }

    @Override
    protected void setUpView(View view) {
        tvTitle.setText("填写订单");
        llGoodsContent.removeAllViews();
        if (null != data && !data.isEmpty()) {
            for (ShoppingCartBeen.MerchantsBean merchantsBean : data) {
                List<ShoppingCartBeen.MerchantsBean.ShoppingCartsBean> shoppingCartsBeans = merchantsBean.getShopping_carts();
                for (ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean : shoppingCartsBeans) {
                    if (shoppingCartsBean.isSelect) {
                        MineGoodsView mineGoodsView = new MineGoodsView(getContext());
                        shoppingCartsBean.inVisiableCheckView = true;
                        mineGoodsView.update(shoppingCartsBean);
                        shopCarIds.append(shoppingCartsBean.getShopping_cart_id());
                        shopCarIds.append(",");
                        llGoodsContent.addView(mineGoodsView);
                    }
                }
            }
        }
        if (isQuickOrder) {
            MineGoodsView mineGoodsView = new MineGoodsView(getContext());
            mineGoodsView.quicksetData(quickOrder);
            llGoodsContent.addView(mineGoodsView);
            totalPrice = quickOrder.getQuantity() * quickOrder.getGoods().getSale_price();
            quickCountCash(couponId, "", quickOrder.getGoods().getGoods_id(), quickOrder.getMerchant_id(), quickOrder.getQuantity());
        } else {
            countCash(couponId, "");
        }
        tvMoney.setText("￥ " + String.valueOf(totalPrice) + " 元");

        tvPeople.setVisibility(View.GONE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.ib_back, R.id.rl_people_infor, R.id.rl_daijinquan, R.id.rl_pay, R.id.tv_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                getActivity().finish();
                break;
            case R.id.rl_people_infor:
                Intent it = new Intent(getContext(), AddressActivity.class);
                it.putExtra("isfromp", false);
                startActivityForResult(it, 1);
                break;
            case R.id.rl_daijinquan:
                Intent itt = new Intent(getContext(), WebActivity.class);
                itt.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, "coupon?");
                startActivityForResult(itt, 10);
                break;
            case R.id.rl_pay:
                if (null == address) {
                    showToast("请选择收货地址");
                    return;
                }

                Intent intent = new Intent(getContext(), ChoosePayWayActivity.class);
                intent.putExtra("cash", payMoney);
                startActivityForResult(intent, CHOICE_WAY);
                break;
            case R.id.tv_pay:
                if (!isQuickOrder) {
                    if (shopCarIds.length() == 0) {
                        showToast("请选择商品");
                        return;
                    }
                }


                if (null == address) {
                    showToast("请选择收货地址");
                    return;
                }

                if (null == bean) {
                    showToast("请选择支付方式");
                    return;
                }

                if (isQuickOrder) {
                    if (bean.getPayment_channel_id() == 5) {//线下打款
                        quickPay(couponId, address.getAddress_id(), bean.getPayment_channel_id(), bean.value, "", UserInfoUtil.AREA_CODE, quickOrder.getQuantity(), quickOrder.getMerchant_id(), quickOrder.getGoods().getGoods_id());
                    } else if (bean.getPayment_channel_id() == 6) {//农资贷
                        quickPay(couponId, address.getAddress_id(), bean.getPayment_channel_id(), "", bean.value, UserInfoUtil.AREA_CODE, quickOrder.getQuantity(), quickOrder.getMerchant_id(), quickOrder.getGoods().getGoods_id());
                    } else {
                        quickPay(couponId, address.getAddress_id(), bean.getPayment_channel_id(), bean.value, bean.value, UserInfoUtil.AREA_CODE, quickOrder.getQuantity(), quickOrder.getMerchant_id(), quickOrder.getGoods().getGoods_id());
                    }

                } else if (bean.getPayment_channel_id() == 5) { //线下打款
                    createOrder(shopCarIds.toString(), address.getAddress_id(), couponId, bean.getPayment_channel_id(), bean.value, "", UserInfoUtil.AREA_CODE);
                } else if (bean.getPayment_channel_id() == 6) {//农资贷
                    createOrder(shopCarIds.toString(), address.getAddress_id(), couponId, bean.getPayment_channel_id(), "", bean.value, UserInfoUtil.AREA_CODE);
                } else {
                    createOrder(shopCarIds.toString(), address.getAddress_id(), couponId, bean.getPayment_channel_id(), "", "", UserInfoUtil.AREA_CODE);
                }

                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                address = (Address.AddressesBean.DataBean) data.getSerializableExtra("Address");
                setAddressShow(address);
                if (isQuickOrder) {
                    quickCountCash(couponId, String.valueOf(address.getAddress_id()), quickOrder.getGoods().getGoods_id(), quickOrder.getMerchant_id(), quickOrder.getQuantity());
                } else {
                    countCash(couponId, String.valueOf(address.getAddress_id()));
                }
                break;
            case CHOICE_WAY:
                bean = (Channels.PaymentChannelsBean) data.getSerializableExtra("payWay");
                //Glide.with(getContext()).load(bean.getIcon()).error(R.mipmap.pay_alipay).into(ivWayPay);
                ivWayPay.setText(bean.getName());
                break;
            case 10://优惠券
                String coupon = data.getStringExtra("coupon");
                if (!TextUtils.isEmpty(coupon)) {
                    try {
                        JSONObject jsonObject = new JSONObject(coupon);
                        couponId = jsonObject.getInt("couponId");
                        money = jsonObject.getDouble("money");
                        Log.e("HQQ", " couponId : " + couponId + " money:  " + money);
                        if (isQuickOrder) {
                            quickCountCash(couponId, String.valueOf(address.getAddress_id()), quickOrder.getGoods().getGoods_id(), quickOrder.getMerchant_id(), quickOrder.getQuantity());
                        } else {
                            countCash(couponId, String.valueOf(address.getAddress_id()));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }

                break;
            default:
                /*************************************************
                 * 步骤3：处理银联手机支付控件返回的支付结果
                 ************************************************/
                if (data == null) {
                    return;
                }

                String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
                String str = data.getExtras().getString("pay_result");
                if (str.equalsIgnoreCase("success")) {

                    // 如果想对结果数据验签，可使用下面这段代码，但建议不验签，直接去商户后台查询交易结果
                    // result_data结构见c）result_data参数说明
                    if (data.hasExtra("result_data")) {
                        String result = data.getExtras().getString("result_data");
                        try {
                            JSONObject resultJson = new JSONObject(result);
                            String sign = resultJson.getString("sign");
                            String dataOrg = resultJson.getString("data");
                            // 此处的verify建议送去商户后台做验签
                            // 如要放在手机端验，则代码必须支持更新证书
                            boolean ret = verify(dataOrg, sign, serverMode);
                            if (ret) {
                                // 验签成功，显示支付结果
                                msg = "支付成功！";
                            } else {
                                // 验签失败
                                msg = "支付失败！";
                            }
                        } catch (JSONException e) {
                        }
                    }
                    // 结果result_data为成功时，去商户后台查询一下再展示成功
                    msg = "支付成功！";
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "用户取消了支付";
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("支付结果通知");
                builder.setMessage(msg);
                builder.setInverseBackgroundForced(true);
                // builder.setCustomTitle();
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
        }
    }

    private void createOrder(final String shopping_cart_ids, int address_id, int coupon_id, int payment_channel_id, String remittance_pic, String loan_end_date, int area_id) {
        String url = API.ORDER_MEMBER +
                "shopping_cart_ids=" + shopping_cart_ids +
                "&address_id=" + address_id +
                "&coupon_id=" + coupon_id +
                "&payment_channel_id=" + payment_channel_id +
                "&remittance_pic=" + remittance_pic +
                "&loan_end_date=" + loan_end_date +
                "&area_id=" + area_id
                + "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        LogUtil.printJ("url=" + url);

        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        switch (payment_channel_id) {

            case 1:    //ailipay
                TypeToken<AliPayBeen> typeToken = new TypeToken<AliPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<AliPayBeen>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(AliPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            EventBus.getDefault().post(REFLUSH_COUNT);
                            doZFBzf(response.getAlipay());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;


            case 2:  //weixinpay
                TypeToken<WeiChatPayBeen> typeoken = new TypeToken<WeiChatPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<WeiChatPayBeen>(typeoken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(WeiChatPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            EventBus.getDefault().post(REFLUSH_COUNT);
                            wxPay(response.getWechat());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;

            case 3:// 银联支付
                TypeToken<UPPayBeen> typoken = new TypeToken<UPPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<UPPayBeen>(typoken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(UPPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            EventBus.getDefault().post(REFLUSH_COUNT);
                            dpUPPay(response.getUnionpay());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;
            default:
                TypeToken<ModelBeen> typken = new TypeToken<ModelBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(ModelBeen response, int id) {
                        if (response.err_code == 0) {
                            showToast("生成订单成功!");
                            EventBus.getDefault().post(REFLUSH_COUNT);
                            getActivity().finish();
                        } else {
                            showToast(response.err_msg);
                        }
                    }
                });
                break;
        }

    }

    private void countCash(final int coupon_id, String address_id) {
        String url = API.ORDER_MEMBER_CALCULATE + "shopping_cart_ids=" + shopCarIds.toString() + "&area_id=" + UserInfoUtil.AREA_CODE + "&coupon_id=" + coupon_id + "&address_id=" + address_id
                + "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<CountCash> typeToken = new TypeToken<CountCash>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<CountCash>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(CountCash response, int id) {
                if (response.getErr_code() == 0) {
                    double pay_money = response.getCalculate_result().getPay_money();
                    payMoney = pay_money;
                    tvPayMoney.setText("实付款： ￥" + pay_money);
                    Address.AddressesBean.DataBean dataBean = response.getCalculate_result().getAddress();
                    if (null != dataBean) {
                        setAddressShow(dataBean);
                    }
                    if (coupon_id != 0) {
                        tvDaijinquan.setText("面值 ¥ " + money);
                        rlDaijinquan.setVisibility(View.VISIBLE);
                    }
                    tvInvoice.setText(response.getCalculate_result().getInvoice_desc());
                } else if (response.getErr_code() == BusinessManager.TOKENTIMEOUT) {
                    UserUtils.getInstance().goToLogin(getActivity());
                    return;
                } else {
                    showToast(response.getErr_msg());
                    if (response.getErr_code() == 31003) {
                        couponId = 0;
                        money = 0;
                        tvDaijinquan.setText("");
                    }
                }
            }
        });
    }


    private void doZFBzf(final String orderSN) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(
                        getActivity());
                final Map<String, String> result = alipay
                        .payV2(orderSN, true);
                Log.i("msp", result.toString());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(result.get("memo"))) {
                            showToast(result.get("memo"));
                        }
                        getActivity().finish();
                    }
                });
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private void wxPay(WeiChatPayBeen.WechatBean wXpayResult) {
        if (!WXEntryUtil.isInstallWeixin(getActivity().getApplicationContext())) {
            showToast("请安装微信客户端");
            return;
        }
        PayReq request = new PayReq();
        request.appId = wXpayResult.getAppid();
        request.partnerId = wXpayResult.getPartnerid();
        request.prepayId = wXpayResult.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wXpayResult.getNoncestr();
        request.timeStamp = wXpayResult.getTimestamp();
        request.sign = wXpayResult.getSign();
        iwxapi.registerApp(Constans.APP_ID);
        iwxapi.sendReq(request);
        getActivity().finish();
    }

    private void dpUPPay(String tn) {
        UPPayAssistEx.startPay(getContext(), null, null, tn, serverMode);
        getActivity().finish();
    }

    private boolean verify(String msg, String sign64, String mode) {
        // 此处的verify，商户需送去商户后台做验签
        return true;

    }

    private void quickPay(int coupon_id, int address_id, int payment_channel_id, String remittance_pic, String loan_end_date, int area_id, int quantity, int merchant_id, int goods_id) {
        String url = API.ORDER_MEMBER_QUICK
                + "coupon_id=" + coupon_id +
                "&address_id=" + address_id +
                "&payment_channel_id=" + payment_channel_id +
                "&remittance_pic=" + remittance_pic +
                "&loan_end_date=" + loan_end_date +
                "&area_id=" + area_id
                + "&quantity=" + quantity
                + "&merchant_id=" + merchant_id
                + "&access_token=" + UserUtils.getInstance().getAuthor().access_token
                + "&goods_id=" + goods_id;

        LogUtil.printJ("url=" + url);
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        switch (payment_channel_id) {
            case 1:
                TypeToken<AliPayBeen> typeToken = new TypeToken<AliPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<AliPayBeen>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(AliPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            doZFBzf(response.getAlipay());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;
            case 2:
                TypeToken<WeiChatPayBeen> typeoken = new TypeToken<WeiChatPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<WeiChatPayBeen>(typeoken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(WeiChatPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            wxPay(response.getWechat());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;
            case 3:

                TypeToken<UPPayBeen> typoken = new TypeToken<UPPayBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<UPPayBeen>(typoken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(UPPayBeen response, int id) {
                        if (response.getErr_code() == 0) {
                            showToast("生成订单成功!");
                            dpUPPay(response.getUnionpay());
                        } else {
                            showToast(response.getErr_msg());
                        }
                    }
                });
                break;
            default:
                TypeToken<ModelBeen> typken = new TypeToken<ModelBeen>() {
                };
                OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(ModelBeen response, int id) {
                        if (response.err_code == 0) {
                            showToast("生成订单成功!");
                            getActivity().finish();
                        } else {
                            showToast(response.err_msg);
                        }
                    }
                });
                break;

        }
    }

    private void quickCountCash(final int coupon_id, String address_id, int goods_id, int merchant_id, int quantity) {
        String url;
        if (address_id.equals("0") || TextUtils.isEmpty(address_id)) {
            url = API.ORDER_MEMBER_QUICK_CALCULATE + "coupon_id=" + coupon_id + "&area_id=" + UserInfoUtil.AREA_CODE + "&goods_id=" + goods_id + "&merchant_id=" + merchant_id + "&quantity=" + quantity
                    + "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        } else {
            url = API.ORDER_MEMBER_QUICK_CALCULATE + "coupon_id=" + coupon_id + "&area_id=" + UserInfoUtil.AREA_CODE + "&goods_id=" + goods_id + "&merchant_id=" + merchant_id + "&quantity=" + quantity
                    + "&access_token=" + UserUtils.getInstance().getAuthor().access_token + "&address_id=" + address_id;
        }
        Log.e("1234", "url=" + url);
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<QuickCalculate> typeToken = new TypeToken<QuickCalculate>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<QuickCalculate>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(QuickCalculate response, int id) {
                if (response.getErr_code() == 0) {
                    double pay_money = response.getCalculate_result().getPay_money();
                    payMoney = pay_money;
                    tvPayMoney.setText("实付款： ￥" + pay_money);
                    Address.AddressesBean.DataBean dataBean = response.getCalculate_result().getAddress();
                    if (null != dataBean) {
                        setAddressShow(dataBean);
                    }
                    if (coupon_id != 0) {
                        tvDaijinquan.setText("面值 ¥ " + money);
                        rlDaijinquan.setVisibility(View.VISIBLE);
                    }
                    tvInvoice.setText(response.getCalculate_result().getInvoice_desc());
                } else if (response.getErr_code() == BusinessManager.TOKENTIMEOUT) {
                    UserUtils.getInstance().goToLogin(getActivity());
                    return;
                } else {
                    showToast(response.getErr_msg());
                    if (response.getErr_code() == 31003) {
                        couponId = 0;
                        money = 0;
                        tvDaijinquan.setText("");
                    }
                }
            }
        });
    }

    private void setAddressShow(Address.AddressesBean.DataBean address) {
        this.address = address;
        String addressDetail = address.getConsignee() + "   " + address.getPhone();
        tvPeople.setText(addressDetail);
        tvPeople.setVisibility(View.VISIBLE);
        tvAddress.setText(address.getProvince_name() + address.getCity_name() + address.getCounty_name() + address.getStreet());
    }

}

